package xiaohuo.fancyring.data

import eos.moe.dragoncore.network.PacketSender
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import taboolib.common.platform.function.submit
import xiaohuo.fancyring.config.ConfigManager

class ShowRingData(private val target: Entity, private val ringList: List<RingData>) {
    private val levelMap = hashMapOf<PositionData, Int>()
    private val playerSet = hashSetOf<Player>()
    var initialization = true

    fun showToPlayer(p: Player) {
        var i = 0
        submit(delay = 0, period = ConfigManager.showInterval) {
            if (i >= ringList.size) {
                playerSet += p
                levelMap.clear()
                initialization = false
                cancel()
            } else {
                with(ringList[i]) {
                    texture.entity = target.uniqueId
                    var level = levelMap[position] ?: 1
                    applyPosition(level)
                    levelMap[position] = level++
                    PacketSender.setPlayerWorldTexture(p, "${target.uniqueId}_魂环_${position}_$level", texture)
                }
            }
            i++
        }
    }

    fun showToPlayer(playerList: List<Player>) {
        var i = 0
        submit(delay = 0, period = ConfigManager.showInterval) {
            if (i >= ringList.size) {
                playerSet += playerList
                levelMap.clear()
                initialization = false
                cancel()
            } else {
                with(ringList[i]) {
                    texture.entity = target.uniqueId
                    var level = levelMap[position] ?: 1
                    applyPosition(level)
                    levelMap[position] = ++level
                    val key = "${target.uniqueId}_魂环_${position}_$level"
                    playerList.forEach {
                        PacketSender.setPlayerWorldTexture(it, key, texture)
                    }
                }
            }
            i++
        }
        playerSet += playerList
        levelMap.clear()
    }

    fun closeShow() {
        playerSet.forEach {
            if (it.isOnline) {
                PacketSender.removePlayerWorldTexture(it, "${target.uniqueId}_魂环", true)
            }
        }
    }
}